package com.delayqueue.registry.netty.handler;

import com.delayqueue.common.enums.MessageType;
import com.delayqueue.common.netty.Address;
import com.delayqueue.common.netty.NettyMessage;
import com.delayqueue.common.netty.NettyUtil;
import com.delayqueue.common.netty.Node;
import com.delayqueue.registry.netty.cache.NodeCacheFactory;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class ConnectInBoundHandler extends ChannelInboundHandlerAdapter {
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        Address address = NettyUtil.getRemoteAddress(ctx);
        log.info("已下线：{}", address);
        NodeCacheFactory.core.delete(address.getIp(), address.getPort());

        Node masterNode = NodeCacheFactory.master.get(address.getIp(), address.getPort());
        if (masterNode != null) {
            NodeCacheFactory.master.delete(address.getIp(), address.getPort());
            NettyMessage nettyMessage = new NettyMessage(MessageType.MASTER_OFFLINE, masterNode.getIp() + ":" + masterNode.getConnectPort());
            NodeCacheFactory.core.broadCastMessage(nettyMessage);
        }
    }
}
